package thread;

class Count {
    private int count = 0;

    public synchronized void add() {
        count++;
    }

    // 两者效果一样
    public void add2() {
        synchronized (this) {
            count++;
        }
    }

    public synchronized static void func() {
        // ...
    }
    // 这两个效果也是一样的
    public static void func2() {
        synchronized (Count.class) {
            // ...
        }
    }

    public int get() {
        return count;
    }
}

public class Demo20 {
    public static void main(String[] args) throws InterruptedException {

        Count count = new Count();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                count.add();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                count.add();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println(count.get());
    }
}
